package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.dto.WmUser;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loginAuth(LoginDto dto) {
        //参数以及账号密码都有不为空
        if (dto == null || (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPhone()) &&
                StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //账号和密码不为空,根据手机号查询
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            //手机号不存在
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //获取加盐后的密码
            String s = dto.getPassword() + one.getSalt();
            //解析密码
            String s1 = DigestUtils.md5DigestAsHex(s.getBytes());
            //如果密码正确,存入token
            if (s1.equals(one.getPassword())) {
                HashMap<String, Object> userMap = new HashMap<>();
                userMap.put("userId", one.getId());
                String token = AppJwtUtil.getToken(userMap);
                HashMap<String, Object> tokenMap = new HashMap<>();
                tokenMap.put("token", token);
                return ResponseResult.okResult(tokenMap);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            }
        //如果用户不登录,使 token为0
            if (!StringUtils.isEmpty(dto.getEquipmentId())) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("userId", 0);
                String token = AppJwtUtil.getToken(map);
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("token", token);
                return ResponseResult.okResult(hashMap);

        }
            return null;
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;
    /**
     * 关注和取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //判断用户是否登录
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建关注实现类
        ApUserFollow apUserFollow=new ApUserFollow();
        apUserFollow.setUserId(user.getUserId());
        ApUser apUser = this.getById(user.getUserId());
        apUserFollow.setUserName(apUser.getName());
        //调用文章作者表
        ResponseResult<ApAuthor> list = articleFeign.list(dto.getAuthorId());
        if (list.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
        ApAuthor author = list.getData();
        if (author!=null){
            //获取作者对应的ap_user_id
            apUserFollow.setFollowId(author.getUserId());
            apUserFollow.setFollowName(author.getName());
        }
        }
        apUserFollow.setLevel(1);
        apUserFollow.setCreatedTime(new Date());
        //判断该用户是否已经添加过该作者
        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
        //根据用户id查找
        query.eq(ApUserFollow::getUserId,apUserFollow.getUserId());
        //根据关注作者id查找
        query.eq(ApUserFollow::getFollowId,apUserFollow.getFollowId());
        ApUserFollow one = followService.getOne(query);
        //如果没有 :新增
        if (one==null){
            if (dto.getOperation()==0) {
                followService.save(apUserFollow);
            }
        }else {
            //如果存在取消关注,删除关注记录
            if (dto.getOperation()==1){
                followService.remove(query);
            }
        }
        return ResponseResult.okResult();
    }
}
